package net.gazhi.delonix.rbac.web.controller;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import net.gazhi.delonix.core.annonation.ApiAction;
import net.gazhi.delonix.core.annonation.ApiController;
import net.gazhi.delonix.core.annonation.ApiLevel;
import net.gazhi.delonix.core.web.AbstractAnnotationController;
import net.gazhi.delonix.rbac.entity.Action;
import net.gazhi.delonix.rbac.entity.Module;
import net.gazhi.delonix.rbac.entity.Role;
import net.gazhi.delonix.rbac.form.RoleEditForm;
import net.gazhi.delonix.rbac.service.ActionService;
import net.gazhi.delonix.rbac.service.RoleService;

@Controller
@ApiController("角色模块")
@RequestMapping("/rbac/role")
public class RoleController extends AbstractAnnotationController {

	@Autowired
	private RoleService roleService;

	@Autowired
	private ActionService actionService;

	@ApiAction(name = "角色列表", level = ApiLevel.SUPER_ADMIN)
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	public ModelAndView list() {
		List<Role> roles = this.roleService.listAll();
		List<Action> actions = this.actionService.list(ApiLevel.GRANT_REQUIRED);
		Set<net.gazhi.delonix.rbac.entity.Controller> controllers = new LinkedHashSet<net.gazhi.delonix.rbac.entity.Controller>();
		Set<Module> modules = new LinkedHashSet<Module>();
		for (Action act : actions) {
			if (!controllers.contains(act.getController())) {
				controllers.add(act.getController());
			}
			if (!modules.contains(act.getController().getModule())) {
				modules.add(act.getController().getModule());
			}
		}
		return new ModelAndView().addObject("roles", roles).addObject("modules", modules).addObject("controllers", controllers).addObject("actions", actions);
	}

	@ApiAction(name = "保存角色", level = ApiLevel.SUPER_ADMIN)
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	public ModelAndView save(@RequestBody @Valid RoleEditForm form, BindingResult result) {
		this.roleService.save(form, result);
		return super.resultView(result);
	}

	@ApiAction(name = "删除角色", level = ApiLevel.SUPER_ADMIN)
	@RequestMapping(path = "/del", method = RequestMethod.GET)
	public ModelAndView del(HttpServletRequest request, int id) {
		BindingResult result = new BeanPropertyBindingResult(new RoleEditForm(), "roleEditForm");
		this.roleService.delete(id, result);
		return super.resultView(result);
	}
}
